package account

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/spf13/cast"

	"github.com/zeromicro/go-zero/core/logx"
	"insighttracking/apps/admin/internal/svc"
	"os"
)

type LogoutApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLogoutApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogoutApiLogic {
	hostname, _ := os.Hostname()
	return &LogoutApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LogoutApiLogic) LogoutApi() (resp string, err error) {
	accountId := l.ctx.Value("accountId")
	// 删除redis数据
	redisKey := fmt.Sprintf("%s_redis_token_%d", "admin", cast.ToInt64(accountId))
	value, _ := l.svcCtx.RedisDb.Get(context.Background(), redisKey).Result()
	if value != "" {
		_, err = l.svcCtx.RedisDb.Del(context.Background(), redisKey).Result()
		_, err = l.svcCtx.RedisDb.Del(context.Background(), value).Result()
		if err != nil {
			return "", errors.New("退出失败")
		}
	}
	return "操作成功", nil
}
